﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace OF.Utility
{
    public class ESBClient
    {
        public string MessageServiceUrl { get; set; }
        public ESBClient(string messageServiceUrl)
        {
            this.MessageServiceUrl = messageServiceUrl;
        }

        public ESBResponseData Publish(ESBMessageEntity message)
        {
            return PostData(message.Topic, message.MessageID, message.MessageData);
        }

        public ESBResponseData Publish<T>(ESBMessageEntity<T> message) 
        {
            return PostData(message.Topic, message.MessageID, message.SerializeMessageData());
        }

        private ESBResponseData PostData(string topic, string messageId, string messageText)
        {
            if(string.IsNullOrWhiteSpace(MessageServiceUrl))
            {
                throw new ArgumentNullException("esb服务地址未配置!");
            }
            WebRequest request = HttpWebRequest.Create(MessageServiceUrl);
            request.Method = "post";
            request.ContentType = "application/x-www-form-urlencoded";

            NameValueCollection nv = new NameValueCollection();
            nv.Add("topic", topic);
            nv.Add("messageid", messageId);
            nv.Add("messagetext", messageText);

            byte[] requestData = BuildRequestData(nv);
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(requestData, 0, requestData.Length);
            }
            ESBResponseData result = null;
            WebResponse response = request.GetResponse();
            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    string responseText = reader.ReadToEnd();
                    result = SerializeHelper.JsonDeserializeFixed<ESBResponseData>(responseText);
                }
            }
            return result;
        }

        private byte[] BuildRequestData(NameValueCollection nv)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string key in nv)
            {
                sb.AppendFormat("{0}={1}&", key, HttpUtility.UrlEncode(nv[key]));
            }
            string data = sb.ToString().TrimEnd('&');
            return Encoding.UTF8.GetBytes(data);
        }
    }
}
